#include <stdio.h>
#include <errno.h>
#include <string.h>
#include <unistd.h>
#include <getopt.h>
#if 0
1. getopt函数的声明
#include <unistd.h>
#include <getopt.h>
int getopt(int argc, char * const argv[], const char *optstring);
extern char *optarg;
extern int optind, opterr, optopt;
2.getopt函数的参数：
参数argc和argv：通常是从main的参数直接传递而来，argc是参数的数量，argv是一个常量字符串数组的地址。
参数optstring：一个包含正确选项字符的字符串，如果一个字符后面有冒号，那么这个选项在传递参数时就需要跟着一个参数。

3.外部变量：
char *optarg：如果有参数，则包含当前选项参数字符串
int optind：argv的当前索引值。当getopt函数在while循环中使用时，剩下的字符串为操作数，下标从optind到argc-1。
我的解释：optind，相当于操作一维数组中的下标变量i，只不过optind值从1开始，由getopt()函数自动给其+1
int opterr：这个变量非零时，getopt()函数为“无效选项”和“缺少参数选项，并输出其错误信息。
我的解释：getopt()出错时给其赋值。
int optopt：当发现无效选项字符之时，getopt()函数或返回 \’ ? \’ 字符，或返回字符 \’ : \’ ，并且optopt包含了所发现的无效选项字符。

#endif

#define N 64

int main(int argc, char *argv[])
{
	int ch;
	int aflag = 0, lflag = 0, tflag = 0, mflag = 0;
	int i;
    
	printf("optind = %d\n", optind);
	opterr = 0;
	if (argc == optind)
	{
		printf("no option\n");
		return 0;
	}

	while ((ch = getopt(argc, argv, "al:t:m")) != -1)
	{
		switch (ch)
		{
			case 'a':
			{
				aflag = 1;
				break;
			}
			case 'l':
			{
				lflag = 1;
				printf("case 'l', optarg = %s\n", optarg);
				break;
			}
			case 't':
			{
				tflag = 1;
				printf("case 't', optarg = %s\n", optarg);
				break;
			}
			case 'm':
			{
				mflag = 1;
				break;
			}
			default:
			{
				printf("wrong, option  = %c\n", (char)optopt);
				printf("opterr = %d\n", opterr);
			}
		}
	}

	printf("aflag = %d lflag = %d\n", aflag, lflag);
	printf("first para argv[%d] = %s, optind = %d\n", optind, argv[optind], optind);
	printf("opterr = %d\n", opterr);


	for(i = 0; i < argc; i++)
	{
		printf("argv[%d]=%s\t", i, argv[i]);
	}
	printf("\n");
	
	return 0;
}
/*
user@user-virtual-machine:~/mywork/PhaseOne/systemprogramming/002/fileio/getopt$ gcc -o mygetopt mygetopt.c 
user@user-virtual-machine:~/mywork/PhaseOne/systemprogramming/002/fileio/getopt$ ./mygetopt -a -l jssj heheh  ehhhe
optind = 1
aflag = 1 lflag = 1
first para argv[3] = jssj, optind = 3
./mygetopt -a -l jssj heheh ehhhe 
user@user-virtual-machine:~/mywork/PhaseOne/systemprogramming/002/fileio/getopt$ ./mygetopt -a  jssj heheh  ehhhe -l hehehhe
optind = 1
aflag = 1 lflag = 1
first para argv[3] = jssj, optind = 3
./mygetopt -a -l jssj heheh ehhhe hehehhe 
user@user-virtual-machine:~/mywork/PhaseOne/systemprogramming/002/fileio/getopt$ ./mygetopt -a  -l
optind = 1
aflag = 1 lflag = 1
first para argv[3] = (null), optind = 3
./mygetopt -a -l 
user@user-virtual-machine:~/mywork/PhaseOne/systemprogramming/002/fileio/getopt$ ./mygetopt -al
optind = 1
aflag = 1 lflag = 1
first para argv[2] = (null), optind = 2
./mygetopt -al 
user@user-virtual-machine:~/mywork/PhaseOne/systemprogramming/002/fileio/getopt$ ./mygetopt -al hhehe hehhe
optind = 1
aflag = 1 lflag = 1
first para argv[2] = hhehe, optind = 2
./mygetopt -al hhehe hehhe 
user@user-virtual-machine:~/mywork/PhaseOne/systemprogramming/002/fileio/getopt$ 
*/
